package InternetCode.Exa4;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.spec.RSAOtherPrimeInfo;

/**
 * 1）获取网络资源的大小
 * 2）下载资源
 */
public class CoreCode {
    public static void main(String[] args) throws IOException {
        String urlStr=" https://cn.bing.com/sa/simg/Flag_Feedback.png";
        System.out.println(urlStr+"的资源大小为："+getResourceLength(urlStr));
        downResource(urlStr);
    }

    /**
     * 给定url地址获取资源的大小（以字节为单位）
     * @param urlStr
     * @return
     * @throws IOException
     */
    public static long getResourceLength(String urlStr) throws IOException {
        URL url=new URL(urlStr);
        URLConnection urlConnection=url.openConnection();
        urlConnection.connect();
        //返回响应报文头字段Content-Length的值
        return urlConnection.getContentLength();
    }

    /**
     * 下载指定url下的文件, 其实就是建立http连接后，通过输入流从网络中读取数据，
     * 然后通过输出流将数据写入硬盘中
     * @param urlStr url
     * @return
     */
    public static void downResource(String urlStr){
        try{
            //创建URL对象
            URL url=new URL(urlStr);
            //获得链接对象
            URLConnection urlConnection=url.openConnection();
            //打开到url引用资源的通信链接
            urlConnection.connect();
            //获得输入流对象
            InputStream inputStream=urlConnection.getInputStream();
            //获得完整路径
            String filePath = url.getFile();
            int pos=filePath.lastIndexOf("/");
            //创建输出流对象
            FileOutputStream out=new FileOutputStream(filePath.substring(pos+1));
            byte[] bytes=new byte[1024];
            int len = inputStream.read(bytes);
            while(len!=-1){
                out.write(bytes,0,len);
                len=inputStream.read(bytes);
            }
            out.close();
            inputStream.close();
            System.out.println("下载完毕！！！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
